﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ext.Net;

namespace KamLib.Ext.Net.Handlers
{

    [UilHandler("ext.grid")]
    public class GridPanelHandler
    {
        [UilMethod]
        public static object GetData(UilMethodArgs e)
        {
            var source = e.Controller as IUilEntitiesSource;
            if (source == null) return null;

            var v = e.Values;
            var group = v.Try("group").To<string>();

            var sort = v.Try("sort").To<string>();
            var dir = v.Try("dir").To<string>();
            var gridfilters = v.Try("gridfilters").To<string>();

            var sortDir = dir.isfull() ? (QueryArgs.SortDirection)Enum.Parse(typeof(QueryArgs.SortDirection), dir, true) : QueryArgs.SortDirection.Default;

            DbFieldID.List flds;
            if (sort.isnull() && (flds = source.SortFields) != null) sort = flds.FirstName();
            if (sort.isnull() && (flds = source.KeyFields) != null) sort = flds.FirstName();

            var we = new QueryArgs
            {
                StartIndex = v.Try("start").To<int?>() ?? 0,
                LimitCount = v.Try("limit").To<int?>() ?? source.PageSize ?? 0,
                SortFields = { new QueryArgs.SortField { Name = sort, Dir = sortDir } },
                TotalExpected = true,
                Filters = NewFilters(gridfilters),
            };

            if (group.isfull())
                we.SortFields.Insert(0, group);

            var list = source.GetData(we);

            var scriptSource = source as IUilJScriptSource;
            var script = scriptSource != null ? scriptSource.Script : null;

            string fieldJson = null;
            var fields = list as IDataReaderFields;
            if (fields != null)
            {
                var sb = new StringBuilder("[");
                for (int i = 0, len = fields.Count; i < len; i++)
                {
                    if (i > 0) sb.Append(',');
                    sb.Append("{name:'");
                    sb.Append(fields.GetName(i));
                    sb.Append("',type:'");
                    sb.Append(ExtUtils.TypeToFieldType(fields.GetFieldType(i)).ToString().ToLower());
                    sb.Append("'}");
                }
                sb.Append(']');
                fieldJson = sb.ToString();
            }

            return new
            {
                data = list,
                total = we.TotalCount,
                fields = fieldJson,
                script
            };
        }


        public static QueryArgs.Filter.List NewFilters(string sfilters)
        {
            if (sfilters.isnull()) return null;

            return new QueryArgs.Filter.List(
                new FilterConditions(sfilters).Conditions.Select(a =>
                    new QueryArgs.Filter(
                        ToUilType(a.FilterType), 
                        a.Name, 
                        a.ValueAsObject(), 
                        ToUilType(a.Comparison)
                    )
                )
            );
        }


        public static FilterType FromUilType(QueryArgs.FilterType value)
        {
            return (FilterType)value;
        }

        public static Comparison FromUilType(QueryArgs.Comparison value)
        {
            return (Comparison)value;
        }

        public static SortDirection FromUilType(QueryArgs.SortDirection value)
        {
            return (SortDirection)value;
        }


        public static QueryArgs.FilterType ToUilType(FilterType value)
        {
            return (QueryArgs.FilterType)value;
        }

        public static QueryArgs.Comparison ToUilType(Comparison value)
        {
            return (QueryArgs.Comparison)value;
        }

        public static QueryArgs.SortDirection ToUilType(SortDirection value)
        {
            return (QueryArgs.SortDirection)value;
        }

    }
}
